// pages/add/index.js

const db = wx.cloud.database();
const todos = db.collection('todos');
const globalData = getApp().globalData;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    images: [],
    address: '',
  },

  location: null,

  afterRead(event) {
    globalData.showLoading('上传中...');
    const { file } = event.detail;
    let count = 0;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    file.forEach(v => {
      wx.cloud.uploadFile({
        cloudPath: v.path.slice(11),
        filePath: v.path,
        success: (res) => {
          this.data.images.push({ url: res.fileID });
          count++;
          if (count === file.length) {
            this.setData({ images: this.data.images });
            globalData.hideLoading();
          }
        },
      });
    })
  },

  async delAllImage() {
    if (this.data.images.length === 0) return;
    globalData.showLoading('删除中...');
    await wx.cloud.deleteFile({
      fileList: this.data.images.map(v => v.url),
    });
    this.data.images.splice(0);
    this.setData({
      images: this.data.images,
    });
    globalData.hideLoading();
  },

  async onDeleteImage(e) {
    globalData.showLoading('删除中...');
    const res = await wx.cloud.deleteFile({
      fileList: [e.detail.file.url],
    });
    if (res.fileList[0].status === 0) {
      this.data.images.splice(e.detail.index, 1);
      this.setData({
        images: this.data.images,
      });
      globalData.hideLoading();
    }
  },

  chooseLocation() {
    wx.chooseLocation({
      success: (location) => {
        this.setData({
          address: location.address,
        });
        this.location = location;
      },
    });
  },

  async onSubmit(e) {
    globalData.showLoading();
    await todos.add({
      data: {
        ...e.detail.value,
        status: 'in-progress',
        images: this.data.images.map(v => v.url),
        location: this.location,
      },
    })
    globalData.Toast.success('添加成功');
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})